package com.pn.taikao.service.impl;

import com.pn.taikao.entity.Exam;
import com.pn.taikao.entity.Paper;
import com.pn.taikao.mapper.ExamMapper;
import com.pn.taikao.mapper.PaperMapper;
import com.pn.taikao.service.ExamService;
import com.pn.taikao.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ExamServiceImpl implements ExamService {

    private final ExamMapper examMapper;
    private final PaperMapper paperMapper;

    public ExamServiceImpl(ExamMapper examMapper, PaperMapper paperMapper) {
        this.examMapper = examMapper;
        this.paperMapper = paperMapper;
    }

    @Override
    @Transactional
    public Long startExam(Long paperId, Long studentId) {
        // 检查是否已经存在考试记录
        Exam existingExam = examMapper.selectByPaperIdAndStudentId(paperId, studentId);
        if (existingExam != null) {
            // 如果考试正在进行中，返回现有考试ID
            if ("in_progress".equals(existingExam.getStatus())) {
                return existingExam.getId();
            }
            // 如果考试已完成，不允许重新开始
            if ("finished".equals(existingExam.getStatus())) {
                throw new RuntimeException("考试已完成，不能重新开始");
            }
        }

        // 获取试卷信息
        Paper paper = paperMapper.selectById(paperId);
        if (paper == null) {
            throw new RuntimeException("试卷不存在");
        }

        // 检查考试时间是否在有效范围内
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(paper.getStartTime())) {
            throw new RuntimeException("考试还未开始");
        }
        if (now.isAfter(paper.getEndTime())) {
            throw new RuntimeException("考试已结束");
        }

        // 创建考试记录
        Exam exam = new Exam();
        exam.setPaperId(paperId);
        exam.setStudentId(studentId);
        exam.setDuration(paper.getDuration());
        exam.setStartTime(now);
        exam.setEndTime(now.plusMinutes(paper.getDuration()));
        exam.setStatus("in_progress");
        exam.setCreateBy("student");
        exam.setCreateTime(now);
        exam.setUpdateTime(now);

        examMapper.insert(exam);
        return exam.getId();
    }

    @Override
    public Exam getById(Long id) {
        return examMapper.selectById(id);
    }

    @Override
    public Exam getByPaperIdAndStudentId(Long paperId, Long studentId) {
        return examMapper.selectByPaperIdAndStudentId(paperId, studentId);
    }

    @Override
    public void updateStatus(Long id, String status) {
        examMapper.updateStatus(id, status);
    }

    @Override
    public void finishExam(Long id) {
        Exam exam = examMapper.selectById(id);
        if (exam == null) {
            throw new RuntimeException("考试不存在");
        }
        if ("finished".equals(exam.getStatus())) {
            return; // 已经完成，无需重复处理
        }
        
        LocalDateTime now = LocalDateTime.now();
        examMapper.updateEndTime(id, now);
        examMapper.updateStatus(id, "finished");
    }

    @Override
    public List<Exam> getByStudentId(Long studentId) {
        return examMapper.selectByStudentId(studentId);
    }

    @Override
    public List<Exam> getByStudentIdAndCourseId(Long studentId, Long courseId) {
        return examMapper.selectByStudentIdAndCourseId(studentId, courseId);
    }

    @Override
    public List<Exam> getByPaperId(Long paperId) {
        return examMapper.selectByPaperId(paperId);
    }

    @Override
    public List<Exam> getPendingGrading(Long teacherId) {
        return examMapper.selectPendingGrading(teacherId);
    }

    @Override
    public List<Exam> getFinishedExams(Long teacherId) {
        return examMapper.selectFinishedExams(teacherId);
    }
}

